package com.nstskj.study.netty.tcp.netty.run;

import com.nstskj.study.netty.tcp.netty.bootstrap.NettyTcpBootstrapService;
import com.nstskj.study.netty.tcp.netty.config.properties.NettyBootServerProperties;
import com.nstskj.study.netty.tcp.netty.init.NetProtoMessageTcpServerChannelInitializer;
import com.nstskj.study.netty.tcp.netty.manage.LocalMananger;
import com.nstskj.study.netty.tcp.netty.manage.spring.LocalSpringBeanManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 20:45
 * @Description netty服务器执行器
 */
@Slf4j
@Component
public class NettyServerExec implements ApplicationRunner, DisposableBean {

    private NettyTcpBootstrapService nettyTcpBootstrapService;

    @Autowired
    private LocalSpringBeanManager localSpringBeanManager;

    /**
     * spring容器启动完成后执行
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化全局spring bean
        LocalMananger instance = LocalMananger.INSTANCE;
        instance.setLocalSpringBeanManager(localSpringBeanManager);
        NettyBootServerProperties nettyBootServerProperties = instance.getLocalSpringBeanManager().getNettyNetDevTcpServerProperties().getNettyBootServerProperties();
        //配置 netty服务器
        this.nettyTcpBootstrapService = new NettyTcpBootstrapService(nettyBootServerProperties.getBossTreadName(),
                nettyBootServerProperties.getWorkThreadName(),
                nettyBootServerProperties.getPort(),
                new NetProtoMessageTcpServerChannelInitializer());
        nettyTcpBootstrapService.startService();
        log.info("netty服务器启动完成 port {}", nettyBootServerProperties.getPort());
    }

    @Override
    public void destroy() throws Exception {
        nettyTcpBootstrapService.stopService();
    }

}
